/*
 * Copyright (C) 2004, Velocityme Partnership
 * NodeAction.java
 *
 * Created on 12 September 2004, 10:18
 */

package com.velocityme.www.interfaces.nodeactions;

import com.velocityme.entity.PermissionBean;
import com.velocityme.interfaces.*;
import com.velocityme.valueobjects.GroupAccessValue;
import com.velocityme.valueobjects.NodeLinkValue;
import com.velocityme.valueobjects.NodeValue;
import com.velocityme.valueobjects.UserAccessValue;
import com.velocityme.www.actionforms.NodeIdActionForm;
import com.velocityme.www.actionforms.NodeLinkIdActionForm;
import com.velocityme.www.actionforms.PostCommentActionForm;
import com.velocityme.www.actionforms.SearchDateActionForm;
import com.velocityme.www.actionforms.nodeactionforms.NodeValueActionForm;
import com.velocityme.www.dto.AccessDTO;
import com.velocityme.www.dto.LinkDTO;
import com.velocityme.www.interfaces.ShowNodeAction;
import com.velocityme.www.utility.NodeUtil;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.actions.DispatchAction;

/**
 *
 * @author  Robert
 */
public class NodeActions extends DispatchAction {
    
    /** Creates a new instance of NodeAction */
    public NodeActions() {
    }
    
    public ActionForward show(ActionMapping mapping, 
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        NodePK nodePK = (NodePK)request.getAttribute("nodePK");
        String selectedTab = (String)request.getAttribute("selectedTab");
        HttpSession session = request.getSession();
        KeySession key = (KeySession)session.getAttribute("sessionKey");
        RemoteClientSession cs = RemoteClientSessionUtil.getHome().create();
        NodeValue nodeValue = cs.getNodeValue(key, nodePK);
        ShowNodeAction.setupTreeDisplay(session, nodeValue, selectedTab);
        return showNode(mapping, form, request, response);
    }
    
    public ActionForward showNode(ActionMapping mapping, 
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        NodePK nodePK = (NodePK)request.getAttribute("nodePK");
        HttpSession session = request.getSession();
        KeySession key = (KeySession)session.getAttribute("sessionKey");
        RemoteClientSession cs = RemoteClientSessionUtil.getHome().create();
        session.setAttribute("nodeValue", cs.getNodeValue(key, nodePK));
        session.setAttribute("nodeHistory", cs.getHistoryValue(key, nodePK));
        return mapping.findForward("ACTION_DISPLAY");
    }
    
    public ActionForward showChangeLog(ActionMapping mapping, 
                                       ActionForm form,
                                       HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
        NodePK nodePK = (NodePK)request.getAttribute("nodePK");
        HttpSession session = request.getSession();
        KeySession key = (KeySession)session.getAttribute("sessionKey");
        RemoteClientSession cs = RemoteClientSessionUtil.getHome().create();
        NodeValue nodeValue = cs.getNodeValue(key, nodePK);
        ShowNodeAction.setupTreeDisplay(session, nodeValue, "Change Log");
        session.setAttribute("changeDeltaValues", cs.getDBObjectChangeDeltaValues(key, new DBObjectPK(nodePK.getNodeId())));
        return mapping.findForward("ACTION_DISPLAY");
    }
    
    public ActionForward showUserAccess(ActionMapping mapping, 
                                       	ActionForm form,
                                       	HttpServletRequest request,
                                       	HttpServletResponse response) throws Exception {
        NodePK nodePK = (NodePK)request.getAttribute("nodePK");
        HttpSession session = request.getSession();
        KeySession key = (KeySession)session.getAttribute("sessionKey");
        RemoteClientSession cs = RemoteClientSessionUtil.getHome().create();
        NodeValue nodeValue = cs.getNodeValue(key, nodePK);
        ShowNodeAction.setupTreeDisplay(session, nodeValue, "User Access");
        Iterator i = cs.getUserAccessByNodeValue(key, nodePK).iterator();
        Collection accessDTOs = new ArrayList();
        PermissionPK permissionUserAccessDelete = new PermissionPK(new Integer(PermissionBean.USER_ACCESS_DELETE));
        while(i.hasNext()) {
            UserAccessValue userAccessValue = (UserAccessValue)i.next();
            Boolean isDeletable = new Boolean(cs.getAssignedPermissions(key, userAccessValue.getNodeValue().getPrimaryKey()).contains(permissionUserAccessDelete));
            Integer userAccessId = userAccessValue.getUserAccessId();
            String nodeName = userAccessValue.getNodeValue().getName();
            String userName = userAccessValue.getUserValue().getNodeValue().getName();
            String roleName = userAccessValue.getRoleValue().getNodeValue().getName();
            accessDTOs.add(new AccessDTO(isDeletable, userAccessId, nodeName, userName, roleName));
        }
        session.setAttribute("userAccessByNode", accessDTOs);
        return mapping.findForward("ACTION_DISPLAY");
    }
    
    public ActionForward showGroupAccess(ActionMapping mapping, 
                                     ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
        NodePK nodePK = (NodePK)request.getAttribute("nodePK");
        HttpSession session = request.getSession();
        KeySession key = (KeySession)session.getAttribute("sessionKey");
        RemoteClientSession cs = RemoteClientSessionUtil.getHome().create();
        NodeValue nodeValue = cs.getNodeValue(key, nodePK);
        ShowNodeAction.setupTreeDisplay(session, nodeValue, "Group Access");
        Iterator i = cs.getGroupAccessByNodeValue(key, nodePK).iterator();
        Collection accessDTOs = new ArrayList();
        PermissionPK permissionGroupAccessDelete = new PermissionPK(new Integer(PermissionBean.GROUP_ACCESS_DELETE));
        while(i.hasNext()) {
            GroupAccessValue groupAccessValue = (GroupAccessValue)i.next();
            Boolean isDeletable = new Boolean(cs.getAssignedPermissions(key, groupAccessValue.getNodeValue().getPrimaryKey()).contains(permissionGroupAccessDelete));
            Integer groupAccessId = groupAccessValue.getGroupAccessId();
            String nodeName = groupAccessValue.getNodeValue().getName();
            String groupName = groupAccessValue.getGroupValue().getNodeValue().getName();
            String roleName = groupAccessValue.getRoleValue().getNodeValue().getName();
            accessDTOs.add(new AccessDTO(isDeletable, groupAccessId, nodeName, groupName, roleName));
        }
        session.setAttribute("groupAccessByNode", accessDTOs);
        return mapping.findForward("ACTION_DISPLAY");
    }
    
    public ActionForward showCreate(ActionMapping mapping, 
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response) throws Exception {
        NodePK nodePK = (NodePK)request.getAttribute("nodePK");
        HttpSession session = request.getSession();
        session.setAttribute("parentNodePK", nodePK);
        session.setAttribute("nodeValue", new NodeValue());
        return mapping.findForward("ACTION_EDIT");
    }
    
    public ActionForward showEdit(ActionMapping mapping, 
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        NodePK nodePK = (NodePK)request.getAttribute("nodePK");
        HttpSession session = request.getSession();
        KeySession key = (KeySession)session.getAttribute("sessionKey");
        RemoteClientSession cs = RemoteClientSessionUtil.getHome().create();
        session.setAttribute("nodeValue", cs.getNodeValue(key, nodePK));
        return mapping.findForward("ACTION_EDIT");
    }
    
    public ActionForward edit(ActionMapping mapping, 
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeySession key = (KeySession)session.getAttribute("sessionKey");
        RemoteClientSession cs = RemoteClientSessionUtil.getHome().create();
        NodePK nodePK;
        if (request.getParameter("btnSubmit").equals("OK")) {
            NodeValue nodeValue = (NodeValue)session.getAttribute("nodeValue");
            nodeValue.setName(((NodeValueActionForm)form).getName());
            nodeValue.setDescription(((NodeValueActionForm)form).getDescription());
            if (nodeValue.nodeIdHasBeenSet()) {
                nodePK = nodeValue.getPrimaryKey();
                cs.nodeEdit(key, nodePK, nodeValue);
            }
            else {
                NodePK parentNodePK = (NodePK)session.getAttribute("parentNodePK");
                nodePK = cs.nodeCreate(key, parentNodePK, nodeValue, "Node");
            }
        }
        // Cancel simply displays the original node again
        else {
            nodePK = new NodePK((Integer)session.getAttribute("nodeId"));
        }
        request.setAttribute("nodePK", nodePK);
        request.setAttribute("selectedTab", "Node");
        return mapping.findForward("ACTION_SUCCESS");
    }
    
    public ActionForward postComment(ActionMapping mapping, 
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeySession key = (KeySession)session.getAttribute("sessionKey");
        RemoteClientSession cs = RemoteClientSessionUtil.getHome().create();
        NodePK nodePK = new NodePK((Integer)session.getAttribute("nodeId"));
        if (request.getParameter("btnSubmit").equals("OK")) {
            PostCommentActionForm postCommentActionForm = (PostCommentActionForm)form;
            String comment = postCommentActionForm.getComment();
            File file = new File(postCommentActionForm.getFile().getFileName());
            String contentType = postCommentActionForm.getFile().getContentType();
            InputStream stream = postCommentActionForm.getFile().getInputStream();
            cs.nodePostComment(key, nodePK, comment, file, contentType, stream);
        }
        request.setAttribute("nodePK", nodePK);
        return mapping.findForward("ACTION_SUCCESS");
    }
    
    public ActionForward delete(ActionMapping mapping,
                                ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeySession key = (KeySession)session.getAttribute("sessionKey");
        RemoteClientSession cs = RemoteClientSessionUtil.getHome().create();
        NodePK nodePK = new NodePK((Integer)session.getAttribute("nodeId"));
        if (request.getParameter("btnSubmit").equals("OK")) {
            NodePK deleteNodePK = new NodePK(((NodeValueActionForm)form).getNodeId());
            nodePK = cs.nodeDelete(key, deleteNodePK);
        }
        NodeValue nodeValue = cs.getNodeValue(key, nodePK);
        request.setAttribute("nodePK", nodePK);
        return mapping.findForward("ACTION_SUCCESS");
    }
    
    public ActionForward showNodeLinks(ActionMapping mapping, 
                                       ActionForm form,
                                       HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
        NodePK nodePK = (NodePK)request.getAttribute("nodePK");
        HttpSession session = request.getSession();
        KeySession key = (KeySession)session.getAttribute("sessionKey");
        RemoteClientSession cs = RemoteClientSessionUtil.getHome().create();
        NodeValue nodeValue = cs.getNodeValue(key, nodePK);
        ShowNodeAction.setupTreeDisplay(session, nodeValue, "Links");
        Iterator i = cs.getNodeLinkValues(key, nodePK).iterator();
        Collection linkDTOs = new ArrayList();
        PermissionPK permissionNodeEdit = new PermissionPK(new Integer(PermissionBean.NODE_EDIT));
        Set assignedPermissions = cs.getAssignedPermissions(key, nodePK);
        boolean isThisDeletable = assignedPermissions.contains(permissionNodeEdit);
        while(i.hasNext()) {
            NodeLinkValue nodeLinkValue = (NodeLinkValue)i.next();
            NodeValue otherNodeValue;
            if (nodeLinkValue.getFromNodeValue().getPrimaryKey().equals(nodePK))
                otherNodeValue = nodeLinkValue.getToNodeValue();
            else
                otherNodeValue = nodeLinkValue.getFromNodeValue();
            boolean isDeletable = false;
            if (isThisDeletable) {
                assignedPermissions = cs.getAssignedPermissions(key, otherNodeValue.getPrimaryKey());
                isDeletable = assignedPermissions.contains(permissionNodeEdit);
            }
            int nodeLinkId = nodeLinkValue.getNodeLinkId().intValue();
            String nodePathName = cs.getNodePathName(key, otherNodeValue.getPrimaryKey());
            linkDTOs.add(new LinkDTO(isDeletable, nodeLinkId, nodePathName));
        }
        session.setAttribute("linkDTOs", linkDTOs);
        if (nodeValue.getType().equals("Task")) {
            session.setAttribute("dependencyLinkDTOs", TaskActions.getDependencyDTOs(key, cs, assignedPermissions, nodePK, true));
            session.setAttribute("dependantLinkDTOs", TaskActions.getDependencyDTOs(key, cs, assignedPermissions, nodePK, false));
        }
        return mapping.findForward("ACTION_DISPLAY");
    }
    
    public ActionForward linkDeleteCheck(ActionMapping mapping, 
                                         ActionForm form,
                                         HttpServletRequest request,
                                         HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        session.setAttribute("linkValue", form);
        return mapping.findForward("ACTION_LINK_DELETE");
    }
    
    public ActionForward linkDelete(ActionMapping mapping, 
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeySession key = (KeySession)session.getAttribute("sessionKey");
        RemoteClientSession cs = RemoteClientSessionUtil.getHome().create();
        NodePK nodePK = new NodePK((Integer)session.getAttribute("nodeId"));
        if (request.getParameter("btnSubmit").equals("OK")) {
            NodeLinkPK nodeLinkPK = new NodeLinkPK(new Integer(((NodeLinkIdActionForm)form).getNodeLinkId()));
            cs.nodeLinkDelete(key, nodeLinkPK);
        }
        request.setAttribute("nodePK", nodePK);
        return mapping.findForward("ACTION_LINK_DELETE_SUCCESS");
    }
    
}
